// 添加全局回调函数类型声明
declare global {
  interface globalThis {
    indexPageRefreshCallback?: () => void;
  }
}

import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import { UserProfile } from './interfaces';

// 应用上下文
export class AppContext {
  // 单例实例
  private static instance: AppContext;
  private context: common.UIAbilityContext | null = null;
  private static readonly PREFERENCES_NAME = 'health_app_preferences';
  private static readonly USER_PROFILE_KEY = 'user_profile';
  
  // 私有构造函数
  private constructor() {
    // 初始化逻辑
  }
  
  // 获取单例实例
  public static getInstance(): AppContext {
    if (!AppContext.instance) {
      AppContext.instance = new AppContext();
    }
    return AppContext.instance;
  }
  
  // 静态设置上下文方法
  public static setContext(context: common.UIAbilityContext): void {
    const instance = AppContext.getInstance();
    instance.context = context;
    console.info('AppContext: 上下文设置成功');
  }
  
  public setContext(context: common.UIAbilityContext): void {
    this.context = context;
  }
  
  public getContext(): common.UIAbilityContext | null {
    return this.context;
  }
  
  // 静态获取上下文方法
  public static getContext(): common.UIAbilityContext | null {
    return AppContext.getInstance().context;
  }

  // 保存用户资料到首选项存储
  public async saveUserProfile(userProfile: UserProfile): Promise<boolean> {
    try {
      if (!this.context) {
        console.error('Context is not initialized');
        return false;
      }
      
      const preferences = await this.getPreferences();
      await preferences.put(AppContext.USER_PROFILE_KEY, JSON.stringify(userProfile));
      await preferences.flush();
      console.info('User profile saved successfully');
      return true;
    } catch (error) {
      console.error(`Failed to save user profile: ${error}`);
      return false;
    }
  }
  
  // 从首选项存储加载用户资料
  public async loadUserProfile(): Promise<UserProfile | null> {
    try {
      if (!this.context) {
        console.error('Context is not initialized');
        return null;
      }
      
      const preferences = await this.getPreferences();
      const profileStr = await preferences.get(AppContext.USER_PROFILE_KEY, '');
      
      if (profileStr && typeof profileStr === 'string') {
        const profile = JSON.parse(profileStr) as UserProfile;
        console.info('User profile loaded successfully');
        return profile;
      }
      
      // 返回默认用户资料
      return this.getDefaultUserProfile();
    } catch (error) {
      console.error(`Failed to load user profile: ${error}`);
      return this.getDefaultUserProfile();
    }
  }
  
  // 获取默认用户资料
  private getDefaultUserProfile(): UserProfile {
    return {
      username: '默认用户',
      gender: '男',
      age: 30,
      height: 170,
      weight: 65,
      avatar: $r('app.media.ic_avatar'),
      bmi: 22.5,
      healthGoals: ['保持健康', '增加运动']
    };
  }
  
  // 获取首选项存储实例
  private async getPreferences(): Promise<preferences.Preferences> {
    if (!this.context) {
      throw new Error('Context is not initialized');
    }
    
    return await preferences.getPreferences(this.context, AppContext.PREFERENCES_NAME);
  }
} 